Page({
  data: {
    sort: 'hot', // 默认按浏览量排序
    works: [], // 初始化为空数组
    isLikeLoading: false, // 点赞加载状态
    
    // 分页相关数据
    pageNum: 1, // 当前页码
    pageSize: 10, // 每页数量
    hasMore: true, // 是否还有更多数据
    isLoading: false, // 是否正在加载
    isRefreshing: false, // 是否正在刷新
    total: 0 // 总数据量
  },

  onLoad() {
    // 加载数据
    this.loadWorks(true);
  },

  onShow() {
    // 页面显示时刷新点赞状态
    this.loadUserLikeStatus();
  },

  // 加载作品数据
  loadWorks(isRefresh = false) {
    if (this.data.isLoading) {
      return;
    }

    // 如果是刷新，重置分页参数
    if (isRefresh) {
      this.setData({
        pageNum: 1,
        hasMore: true,
        works: []
      });
    }

    // 如果没有更多数据，直接返回
    if (!this.data.hasMore && !isRefresh) {
      return;
    }

    this.setData({
      isLoading: true,
      isRefreshing: isRefresh
    });

    // 显示加载提示
    if (isRefresh) {
      wx.showLoading({
        title: '刷新中...',
        mask: true
      });
    }
  
    // 从 Storage 中获取 token
    let token = '';
    try {
      token = wx.getStorageSync('token'); 
    } catch (e) {
      console.error('获取 token 失败', e);
    }

    // 构建请求参数
    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      sort: this.data.sort
    };

    // 发起网络请求
    wx.request({
      url: `http://localhost:8080/works/works/listAll`,
      method: 'GET',
      data: params,
      header:{
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('请求返回的原始数据：', res.data);
        if (res.data.code === 200 && res.data.data) {
          const responseData = res.data.data;
          let newWorks = [];
          
          // 处理分页数据
          if (responseData.list && Array.isArray(responseData.list)) {
            // 后端返回分页数据格式
            newWorks = responseData.list;
            this.setData({
              total: responseData.total || 0,
              hasMore: this.data.pageNum * this.data.pageSize < (responseData.total || 0)
            });
          } else if (Array.isArray(responseData)) {
            // 后端返回数组格式（兼容原有接口）
            newWorks = responseData;
            this.setData({
              hasMore: responseData.length === this.data.pageSize
            });
          }

          // 映射接口数据到页面所需格式
          const formattedWorks = newWorks.map(item => {
            // 处理多图，将逗号分隔的图片地址转为数组
            const images = item.coverImg ? item.coverImg.split(',') : [];
            console.log('图片路径：', images)
            return ({
              id: item.workId,
              authorId: item.authorId,
              avatar: item.authorAvatar,
              username: item.authorNickname,
              publishTime: this.formatTime(item.workCreateTime),
              rawCreateTime: item.workCreateTime, // 保存原始时间用于排序
              title: this.cleanHtmlTags(item.title),
              images: images,
              likeCount: item.likeCount || 0,
              commentCount: item.commentCount || 0,
              viewCount: item.viewCount || 0,
              isLiked: false
            });
          });

          // 更新数据
          if (isRefresh) {
            // 刷新时替换所有数据
            this.setData({
              works: formattedWorks
            }, () => {
              this.sortWorks(); // 数据加载完成后排序
              this.loadUserLikeStatus();
            });
          } else {
            // 加载更多时追加数据
            this.setData({
              works: [...this.data.works, ...formattedWorks],
              pageNum: this.data.pageNum + 1
            }, () => {
              this.sortWorks(); // 数据加载完成后排序
              this.loadUserLikeStatus();
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('数据加载失败', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({
          isLoading: false,
          isRefreshing: false
        });
        wx.hideLoading();
        
        // 停止下拉刷新
        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 时间格式化工具函数
  formatTime(timeStr) {
    const now = new Date();
    const createTime = new Date(timeStr);
    const diffMs = now - createTime;
    const diffMinutes = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMinutes / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${createTime.getMonth() + 1}-${createTime.getDate()}`;
    }
  },

  // 切换排序方式
  changeSort(e) {
    const sort = e.currentTarget.dataset.sort;
    // 打印日志确认是否触发切换
    console.log('切换排序方式为:', sort);
    this.setData({ sort }, () => {
      // 切换排序时重新加载数据
      this.loadWorks(true);
    });
  },

  // 排序作品 - 修复版
  sortWorks() {
    const { works, sort } = this.data;
    // 创建副本避免直接修改原数组
    const sortedWorks = [...works];
    
    console.log('当前排序方式:', sort, '排序前:', sortedWorks);
    
    if (sort === 'hot') {
      // 按浏览量降序
      sortedWorks.sort((a, b) => {
        const result = (b.likeCount || 0) - (a.likeCount33333  || 0);
        // console.log('按浏览量排序结果:', result);
        return result;
      });
    } else if (sort === 'new') {
      // 按原始发布时间降序（最新的在前）
      sortedWorks.sort((a, b) => {
        const timeA = new Date(a.rawCreateTime).getTime();
        const timeB = new Date(b.rawCreateTime).getTime();
        const result = timeB - timeA;
        // console.log('按时间排序结果:', result);
        return result;
      });
    }

    this.setData({ works: sortedWorks }, () => {
      console.log('排序后的数据:', sortedWorks);
    });
  },

  // 处理点赞
  handleLike(e) {
    // 防止重复点击
    if (this.data.isLikeLoading) {
      return;
    }

    const workId = e.currentTarget.dataset.id;
    const workIndex = this.data.works.findIndex(item => item.id === workId);
    
    if (workIndex === -1) {
      console.error('未找到对应作品');
      return;
    }

    const currentWork = this.data.works[workIndex];
    const isCurrentlyLiked = currentWork.isLiked;
    
    // 获取用户信息
    let userInfo = null;
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
    }

    if (!userInfo || !userInfo.id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 乐观更新UI
    const originalWorks = [...this.data.works];
    const updatedWorks = [...this.data.works];
    updatedWorks[workIndex] = {
      ...currentWork,
      isLiked: !isCurrentlyLiked,
      likeCount: isCurrentlyLiked ? Math.max(0, currentWork.likeCount - 1) : currentWork.likeCount + 1
    };

    this.setData({
      works: updatedWorks,
      isLikeLoading: true
    });

    // 发送请求到后端
    wx.request({
      url: 'http://localhost:8080/likes/likes/redisLike',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        likerUid: userInfo.id,
        authorUid: currentWork.authorId,
        targetId: currentWork.id,
        targetType: 1
      },
      success: (res) => {
        console.log('点赞请求响应:', res.data);
        
        if (res.data.code === 200) {
          // 成功，使用后端返回的数据更新UI
          const result = res.data.data;
          const finalWorks = [...this.data.works];
          finalWorks[workIndex] = {
            ...finalWorks[workIndex],
            likeCount: result.likeCount || finalWorks[workIndex].likeCount
          };
          
          this.setData({ works: finalWorks });
          
          wx.showToast({
            title: result.message || (isCurrentlyLiked ? '取消点赞成功' : '点赞成功'),
            icon: 'success'
          });
        } else {
          // 失败，回滚UI
          this.setData({ works: originalWorks });
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('点赞请求失败:', err);
        // 网络错误，回滚UI
        this.setData({ works: originalWorks });
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLikeLoading: false });
      }
    });
  },

  // 加载用户点赞状态
  loadUserLikeStatus() {
    const { works } = this.data;
    if (works.length === 0) {
      return;
    }

    // 获取用户信息
    let userInfo = null;
    try {
      userInfo = wx.getStorageSync('userInfo');
    } catch (e) {
      console.error('获取用户信息失败', e);
      return;
    }

    if (!userInfo || !userInfo.id) {
      return;
    }

    // 获取token
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    // 获取作品ID列表
    const workIds = works.map(work => work.id);

    // 请求用户点赞状态
    wx.request({
      url: 'http://localhost:8080/likes/likes/getUserLikeStatus',
      method: 'POST',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        userId: userInfo.id,
        targetIds: workIds,
        targetType: 1
      },
      success: (res) => {
        console.log('获取点赞状态响应:', res.data);
        
        if (res.data.code === 200) {
          const likedIds = res.data.data || [];
          const updatedWorks = this.data.works.map(work => ({
            ...work,
            isLiked: likedIds.includes(work.id)
          }));
          
          this.setData({ works: updatedWorks });
        }
      },
      fail: (err) => {
        console.error('获取点赞状态失败:', err);
      }
    });
  },

  // 跳转到作品详情
  toWorkDetail(e) {
    const workId = e.currentTarget.dataset.id;
    const authorId = e.currentTarget.dataset.authorId;
    console.log('作品ID:', workId, '作者ID:', authorId);
    wx.navigateTo({
      url: `/find/pages/findDetail/findDetail?id=${workId}&authorId=${authorId}`
    });
  },

  toUserDetail(e){
    const authorId = e.currentTarget.dataset.authorId;
    console.log('作者ID:', authorId, '类型:', typeof authorId);
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?userId=${authorId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    console.log('触发下拉刷新');
    this.loadWorks(true);
  },

  // 上拉加载更多
  onReachBottom() {
    console.log('触发上拉加载更多');
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadWorks(false);
    } else if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
    }
  },

  // 清理HTML标签
  cleanHtmlTags(html) {
    if (!html) return '';
    // 移除HTML标签，保留文本内容
    return html.replace(/<[^>]*>/g, '');
  }



});
